
#ifndef ThreeDBeamQuality_H
#define ThreeDBeamQuality_H

#include <QtOpenGLWidgets/QtOpenGLWidgets>
#include <QOpenGLFunctions>
#include <utility>
#include <QOpenGLTexture>
#include <QImage>
#include <cmath>

#include "ThreeD_Ellipse.hpp"

class ThreeDBeamQuality : public QOpenGLWidget, protected QOpenGLFunctions {
    Q_OBJECT

public:
    explicit ThreeDBeamQuality(QWidget *parent = nullptr);

    ~ThreeDBeamQuality();

    void addEllipse(float xPos, float major, float minor, float angle, const QImage &textureImage);
    void removeEllipse(float xPos);
    void clear();
    void refresh();
    std::vector<char> ellipsesVisible;

protected:

    void initializeGL() override;
    void paintGL() override;
    static float calculateOptimalTickInterval(float minVal, float maxVal);
    static QString formatTickLabel(float value);
    static void naturalCubicSpline(const std::vector<float> &x, const std::vector<float> &y, std::vector<float> &y2);
    static float cubicSplineInterpolate(float x0, float x1, float y0, float y1, float y20, float y21, float x);
    static float mapXCoordinate(float originalX, float dataMinX, float scaleFactor) ;
    static void calculateSectionPoints(const MyEllipse& ellipse, float mappedX, std::vector<std::pair<float, float>>& yPos, std::vector<std::pair<float, float>>& yNeg,
                              std::vector<std::pair<float, float>>& zPos,
                              std::vector<std::pair<float, float>>& zNeg) ;
    void drawHighQualityCurve(const std::vector<std::pair<float, float>>& points,bool isYSection, const float color[4]);
    void drawSectionCurves(const std::vector<std::pair<float, float>>& yPos,const std::vector<std::pair<float, float>>& yNeg,const std::vector<std::pair<float, float>>& zPos,
                          const std::vector<std::pair<float, float>>& zNeg) ;

    void drawEllipseLabel(float xPos, float originalX, const MyEllipse &ellipse, size_t index);

    void resizeGL(int w, int h) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;


private:
    float rotationX = 0;
    float rotationY = 0;
    QPointF lastPos;
    float axisLength = 0;
    float tickInterval = 0;
    float scale = 0;
    std::vector<MyEllipse> ellipses;
    QTimer* m_updateTimer;
    bool m_pendingUpdate = false;

};

#endif